<?php

App::uses('AppController', 'Controller');

class OccurrencesController extends AppController
{
    public $name = 'Occurrences';
    public $uses = array('Occurrence','UsersOccurrences', 'Establishment', 'Institution', 'Individual', 'Guide', 'History', 'Teste');
    
    public function beforeFilter()
    {
        parent::beforeFilter();
    }
    
    public function index()
    {
        $Occurrences = $this->Occurrence->find('all');
        $occurrences_info['count'] = $this->Occurrence->find('count');
        $occurrences_info['review'] = $this->UsersOccurrences->find('count', array('conditions'=>array('Occurrence.status'=>'Não Autorizada')));
        $occurrences_info['resolved'] = $this->UsersOccurrences->find('count', array('conditions'=>array('Occurrence.status'=>'Solucionada')));
        $occurrences_info['pending'] = $this->UsersOccurrences->find('count', array('conditions'=>array('Occurrence.status'=>'Não Solucionada')));
        $this->set('occurrences_info',$occurrences_info);
    }
    
    
    function view($status=null, $protocol=null)
    {
        
        if($status==null)
        {
            $usuarios_ocorrencias = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                'conditions' => array('Occurrence.status' => 'Não Solucionada')));

            $titulo = "Ocorrências Pendentes";

        }
        else if($status == 'resolved')
        {
            $usuarios_ocorrencias = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                'conditions' => array('Occurrence.status' => 'Solucionada')));
            $titulo = "Ocorrências Solucionadas";

        }
        else if($status == 'new')
        {
            $usuarios_ocorrencias = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                'conditions' => array('Occurrence.status' => 'Não Autorizada')));
            $titulo = "Ocorrências em Análise";

        }
        else if($status == 'search')
        {
            $usuarios_ocorrencias = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                'conditions' => array('protocol' => $protocol)));
            $titulo = "Busca de Ocorrências";
        }
        
        $this->set('titulo',$titulo);
        $this->set('status',$status);
            
        $options_destinos = $this->Institution->find('list', array('fields' => array('id','name')));
        $this->set('options_destinos', $options_destinos);
        
        $this->set('usuarios_ocorrencias', $usuarios_ocorrencias);
      
    }
    
    
    function search($type=null)
    {
        $this->set('titulo', 'Pesquisar Ocorrência');
        
        $all_guides = $this->Guide->find('list');
        $this->set('all_guides', array_merge(array('0'=>'Selecione'),$all_guides));
        
        $this->set('status','');//completar
        
        if($this->request->data)
        {
//            die(debug($this->data));
            
            switch($this->request->data['Occurrence']['search_type'])
            {
                case "protocol":
                    $usuarios_ocorrencias = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                    'conditions' => array('UsersOccurrences.protocol' => $this->request->data['Occurrence']['protocolo'])));
                    $this->set('usuarios_ocorrencias', $usuarios_ocorrencias);
                break;
                
                case "cpf":
                    $usuarios_ocorrencias = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                    'conditions' => array('Occurrence.cpf' => $this->request->data['Occurrence']['cpf'])));
                    $this->set('usuarios_ocorrencias', $usuarios_ocorrencias);
                break;
                
                case "guide":
                    $usuarios_ocorrencias = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                    'conditions' => array('Occurrence.guide_id' => $this->request->data['Occurrence']['guia'])));
                    $this->set('usuarios_ocorrencias', $usuarios_ocorrencias);
                break;
                
                case "establishment":
                    $usuarios_ocorrencias = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                    'conditions' => array('Occurrence.establishment_id' => $this->request->data['Occurrence']['estabelecimento'])));
                    $this->set('usuarios_ocorrencias', $usuarios_ocorrencias);
                break;
                
                case "date":
                    $usuarios_ocorrencias = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                    'conditions' => array('Occurrence.date' => $this->request->data['Occurrence']['data'])));
                    $this->set('usuarios_ocorrencias', $usuarios_ocorrencias);
                break;
                default:
                break;
            }
        }
    }
    
    
    function reports($status=null, $protocol=null)
    {
        $this->layout = 'print';
        
            $occurrences = $this->UsersOccurrences->find('all', array('recursive'=>2, 'fields' => '',
                'conditions' => array('')));
            
            $this->set('occurrences', $occurrences);

    }

    function add($institute_type)
    {
        $this->set('institute_type', $institute_type);
        
        // Definição de instituições. (Instituição, Pessoa Física e Guia de Turismo)
        $occurrence_establishments = $this->Establishment->find('list', array('fields' => array('id','name'), 'order'=>array('name')));
        $this->set('occurrence_establishments', $occurrence_establishments);
        
        $occurrence_individuals = $this->Individual->find('list', array('fields' => array('id','name'), 'order'=>array('name')));
        $this->set('occurrence_individuals', $occurrence_individuals);
        
        $occurrence_guides = $this->Guide->find('list', array('fields' => array('id','name'), 'order'=>array('name')));
        $this->set('occurrence_guides', $occurrence_guides);
        
        // Outra coisa. (Comentar)
        $occurrence_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name')));
        $this->set('occurrence_institutions', $occurrence_institutions);

        $occurrence_origins = $this->Occurrence->getEnumValues('origin');
        $this->set('occurrence_origins', $occurrence_origins);

        $occurrence_types = $this->Occurrence->getEnumValues('type');
        $this->set('occurrence_types', $occurrence_types);

        $occurrence_private_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name'),
            'conditions' => array('type'=>'Privado')));
        $this->set('occurrence_private_institutions', $occurrence_private_institutions);

        $occurrence_public_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name'),
            'conditions' => array('type'=>'publico')));
        $this->set('occurrence_public_institutions', $occurrence_public_institutions);

        $occurrence_partners_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name'),
            'conditions' => array('partner'=>'Sim')));
        $this->set('occurrence_partners_institutions', $occurrence_partners_institutions);

        $occurrence_notpartners_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name'),
            'conditions' => array('partner'=>'Não')));
        $this->set('occurrence_notpartners_institutions', $occurrence_notpartners_institutions);
        
        $enviar = false;
        
        
        if($this->request->is('post'))
        {
            //die(debug($this->request->data));
            if(empty($this->request->data['Occurrence']['cpf']))
            {
                $enviar = true;   
            }
            else
            {
                if($this->VALIDACPF($this->request->data['Occurrence']['cpf'],$cpf) == 0)
                {
                    $envia = false;
                    $this->Session->setFlash('<div class="alert alert-error">CPF INVÁLIDO!</div>');
                }
                else
                {
                    $enviar = true;
                }
            }
            
            if($enviar)
            {         
                $this->request->data['Occurrence']['date'] = $this->dataPortugues($this->request->data['Occurrence']['date']);
                $this->request->data['Occurrence']['status'] = 'Não Autorizada';

                if(isset($this->request->data['Occurrence']['guide_id']) ||
                    isset($this->request->data['Occurrence']['establishment_id']) ||
                    isset($this->request->data['Occurrence']['individual_id']))
                { 

                    $this->Occurrence->save($this->request->data['Occurrence']);

                    $this->request->data['UsersOccurrences']['occurrence_id'] = $this->Occurrence->getLastInsertID();
                    $this->request->data['UsersOccurrences']['protocol'] = 0;

                    $this->UsersOccurrences->save($this->request->data['UsersOccurrences']);

                    $ultima_ocorrencia = $this->UsersOccurrences->getLastInsertID();
                    $info_ultima_ocorrencia = $this->UsersOccurrences->read(null, $ultima_ocorrencia);

                    $protocol = $info_ultima_ocorrencia['Occurrence']['created'].$ultima_ocorrencia;
                    $protocol = str_replace('-', '', $protocol);
                    $protocol = str_replace(' ', '', $protocol);
                    $protocol = str_replace(':', '', $protocol);

                    $this->UsersOccurrences->save(array(
                        'id' => $ultima_ocorrencia,
                        'protocol' => $protocol,
                        'user_id' => $this->Auth->user('id')
                    ));
                    
                    //die(debug($this->data));
                    
                    
                    $this->Session->setFlash('<div class="alert alert-success">Seu protocolo é:' . $protocol . "</div>");
                    $this->redirect(array('controller' => 'testes', 'action' => 'add',$this->Occurrence->getLastInsertID()));
                }
                else
                {
                    $this->Session->setFlash('<div class="alert alert-error">Verifique se a empresa está cadastrada!</div>');
                }
            }
        }
    }
    function edit($institute_type, $id)
    {
        $this->set('institute_type',$institute_type);
        
        // Definição de instituições. (Instituição, Pessoa Física e Guia de Turismo)
        $occurrence_establishments = $this->Establishment->find('list', array('fields' => array('id','name'), 'order'=>array('name')));
        $this->set('occurrence_establishments', $occurrence_establishments);
        
        $occurrence_individuals = $this->Individual->find('list', array('fields' => array('id','name'), 'order'=>array('name')));
        $this->set('occurrence_individuals', $occurrence_individuals);
        
        $occurrence_guides = $this->Guide->find('list', array('fields' => array('id','name'), 'order'=>array('name')));
        $this->set('occurrence_guides', $occurrence_guides);
        
        // Outra coisa. (Comentar)
        $occurrence_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name')));
        $this->set('occurrence_institutions', $occurrence_institutions);

        $occurrence_origins = $this->Occurrence->getEnumValues('origin');
        $this->set('occurrence_origins', $occurrence_origins);

        $occurrence_types = $this->Occurrence->getEnumValues('type');
        $this->set('occurrence_types', $occurrence_types);

        $occurrence_private_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name'),
            'conditions' => array('type'=>'Privado')));
        $this->set('occurrence_private_institutions', $occurrence_private_institutions);

        $occurrence_public_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name'),
            'conditions' => array('type'=>'publico')));
        $this->set('occurrence_public_institutions', $occurrence_public_institutions);

        $occurrence_partners_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name'),
            'conditions' => array('partner'=>'Sim')));
        $this->set('occurrence_partners_institutions', $occurrence_partners_institutions);

        $occurrence_notpartners_institutions = $this->Institution->find('list', array('fields' => array('id','name'), 'order'=>array('name'),
            'conditions' => array('partner'=>'Não')));
        $this->set('occurrence_notpartners_institutions', $occurrence_notpartners_institutions);
        
        $enviar = false;
        
        
        if($this->request->is('post'))
        {
            //die(debug($this->request->data));
            if(empty($this->request->data['Occurrence']['cpf']))
            {
                $enviar = true;   
            }
            else
            {
                if($this->VALIDACPF($this->request->data['Occurrence']['cpf'],$cpf) == 0)
                {
                    $envia = false;
                    $this->Session->setFlash('<div class="alert alert-error">CPF INVÁLIDO!</div>');
                }
                else
                {
                    $enviar = true;
                }
            }
            
            if($enviar)
            {         
                $this->request->data['Occurrence']['date'] = $this->dataPortugues($this->request->data['Occurrence']['date']);
                $this->request->data['Occurrence']['status'] = 'Não Autorizada';

                if(isset($this->request->data['Occurrence']['guide_id']) ||
                    isset($this->request->data['Occurrence']['establishment_id']) ||
                    isset($this->request->data['Occurrence']['individual_id']))
                { 

                    $this->Occurrence->save($this->request->data['Occurrence']);

                    $this->request->data['UsersOccurrences']['occurrence_id'] = $this->Occurrence->getLastInsertID();
                    $this->request->data['UsersOccurrences']['protocol'] = 0;

                    $this->UsersOccurrences->save($this->request->data['UsersOccurrences']);

                    $ultima_ocorrencia = $this->UsersOccurrences->getLastInsertID();
                    $info_ultima_ocorrencia = $this->UsersOccurrences->read(null, $ultima_ocorrencia);

                    $protocol = $info_ultima_ocorrencia['Occurrence']['created'].$ultima_ocorrencia;
                    $protocol = str_replace('-', '', $protocol);
                    $protocol = str_replace(' ', '', $protocol);
                    $protocol = str_replace(':', '', $protocol);

                    $this->UsersOccurrences->save(array(
                        'id' => $ultima_ocorrencia,
                        'protocol' => $protocol,
                        'user_id' => $this->Auth->user('id')
                    ));
                    
                    //die(debug($this->data));
                    
                    
                    $this->Session->setFlash('<div class="alert alert-success">Seu protocolo é:' . $protocol . "</div>");
                    $this->redirect(array('controller' => 'testes', 'action' => 'add',$this->Occurrence->getLastInsertID()));
                }
                else
                {
                    $this->Session->setFlash('<div class="alert alert-error">Verifique se a empresa está cadastrada!</div>');
                }
            }
        }
        else
         {
            $this->request->data = $this->Occurrence->read(null,$id);
         }
    }
    
  
    
    
    function authorize($id=null)
    {
        $send_mail = true; //ativa e desativa o envio de e-mails (para trabalhar local e remoto)
        $usuario_info = $this->Session->read('Auth'); // #POG
        $this->set('usuario_info', $usuario_info);
        
        $qtd_ocorrencias = $this->Occurrence->find('count', array('recursive'=>2, 'fields' => '','conditions' => array('Occurrence.id' => $id)));
        $this->set('qtd_ocorrencias', $qtd_ocorrencias);

        // Definição de instituições. (Instituição, Pessoa Física e Guia de Turismo)
        $occurrence_institutions = $this->Institution->find('list', array('fields' => array('id','name')));
        $this->set('occurrence_institutions', $occurrence_institutions);
//        die(debug($occurrence_institutions));
        
        if($this->request->data)
        {
           
            
            $id = $this->data['Occurrence']['id'];
                //die($id);
                
                $empresa[0] = $this->Institution->find('first', array('conditions' => array('id' => $this->data['Empresa']['nome1'])));
                
                if($this->data['Empresa']['nome2'] != 0)
                {
                    $empresa[1] = $this->Institution->find('first', array('conditions' => array('id' => $this->data['Empresa']['nome2'])));
                }
              
                if($this->data['Empresa']['nome3'] != 0)
                {
                    $empresa[2] = $this->Institution->find('first', array('conditions' => array('id' => $this->data['Empresa']['nome3'])));
                }
                

                if($this->data['Occurrence']['date_solution'] < $this->dataPortugues($this->data['Occurrence']['date']))
                {
                    $this->Session->setFlash('<div class="alert alert-error">O prazo dado para a solução  é menor que a data do recebimento!</div>');
                    //$this->redirect(array('action' => 'autorizar/'.$id));
                }
                else if($this->data['Occurrence']['date_solution'] < date('d-m-Y'))
                {
                    $this->Session->setFlash('<div class="alert alert-error">O prazo dado para a solução é Menor que a data Atual!</div>');
                    //$this->redirect(array('action' => 'autorizar/'.$id));
                }
                else
                {
                     
                    
                    $this->request->data['Occurrence']['date_solution'] = $this->dataPortugues($this->data['Occurrence']['date_solution']);
                     
//                    $this->data['Occurrence']['status'] = 'Não solucionada'; //#POG
                    
                    
                    $this->Occurrence->set(array(
                        'status' => 'Não solucionada'
                    ));
                    
//                    die(debug($this->data['Occurrence']));
                    $this->Occurrence->save($this->data['Occurrence']);
                    
                    $this->loadModel('History');
                    for($i=0;$i<1;$i++)
                    {
                        if($empresa[$i] != 0)
                        {
                            $this->History->create();
                            $log['History']['user_id'] = $this->Auth->user('id');
                            $log['History']['occurrence_id'] = $id;
                            $log['History']['institution_id'] = $empresa[$i]['Institution']['id'];
                            $log['History']['date_solution'] = $this->data['Occurrence']['date'];
                            $log['History']['providence'] = $this->data['Occurrence']['description_solution'];
                            $log['History']['action'] = 'Autorizou';
                            $log['History']['protocol'] = $this->data['UsersOccurrences']['protocol'];
                            $this->History->save($log);
                        }
                    }
                    
                    
                    $institution_sended = $this->Institution->find('first', array('conditions' => array('id'=>$empresa[0]['Institution']['id'])));
                    $occurrence_editing = $this->Occurrence->find('first', array('recursive'=>2, 'fields' => '','conditions' => array('Occurrence.id' => $id)));
                    
                    $this->loadModel('Teste');
                    $img_send = $this->Teste->find('first', array('conditions' => array('occurrence_id' => $id)));
                    
                    // Início do envio de e-mail
                    $content['to'] = $occurrence_editing['Occurrence']['email'];
                    $content['subject'] = 'Ocorrência';
                    $content['content'] = '<h1>Ocorrência</h1>';
                    $content['content'] .= '<p>Olá, '.$occurrence_editing['Occurrence']['name'].'</p>';
                    $content['content'] .= '<p>A sua ocorrência foi enviada para a instituição '.$empresa[0]['Institution']['name'].'</p>';
                    if($send_mail)$this->enviaremail($content);
                    
                    
                    $content['to'] = $institution_sended['Institution']['email'];
                    $content['subject'] = 'Ocorrência';
                    $content['content'] = '<h1>Atenção: Você tem uma ocorrência na TurisRio</h1>';
                    $content['content'] .= '<p>Descrição:'.$occurrence_editing['Occurrence']['description'].'</p>';
                    $content['content'] .= '<p>Solução proposta:'.$occurrence_editing['Occurrence']['description_solution'].'</p>';
                    if(!empty($img_send))
                    {
                        $content['content'] .= '</br></br> <img src="http://techtour.esfinge.org/'.$img_send['Teste']['dir'].'/'.$img_send['Teste']['filename'].'" style="width: 100%;"/>';
                    }
                    if($send_mail)$this->enviaremail($content);
                    // Fim do envio de e-mail
                    $this->Session->setFlash('<div class="alert alert-success">Autorizado com sucesso!</div>');
                    $this->request->data['Occurrence']['date_solution'] = $this->dataPortugues($this->data['Occurrence']['date_solution']);
                }
                
        }
        else
        {
            $this->data = $this->UsersOccurrences->find('first', array('recursive'=>2, 'fields' => '','conditions' => array('Occurrence.id' => $id)));
            $this->request->data['Occurrence']['date_solution'] = $this->dataPortugues($this->data['Occurrence']['date_solution']);
        }
    }
    
    function reanalyse($id)
    {
        $users_occurrence = $this->UsersOccurrences->find('first', array('Occurrence.id'=>$id));
        
        
        if($this->request->data)
        {
            $this->request->data['UsersOccurrences']['id'] = $users_occurrence['UsersOccurrences']['id'];
            $this->request->data['Occurrence']['status'] = 1;
            $this->request->data['Occurrence']['date_solution'] = '0000-00-00';
            
            
            //die(debug($this->data));
            //$this->UsersOccurrences->save($this->data);
            $this->Occurrence->save($this->data);
            
            $this->History->create();
            $log['History']['user_id'] = $this->Auth->user('id');
            $log['History']['occurrence_id'] = $id;
            $log['History']['institution_id'] = $users_occurrence['Occurrence']['institution_id'];
            $log['History']['date_solution'] = $users_occurrence['Occurrence']['date_solution'];
            $log['History']['answer_email'] = $this->data['Occurrence']['solution'];
            $log['History']['providence'] = $this->data['Occurrence']['description_solution'];
            $log['History']['action'] = 'Volta para Analise';
            $log['History']['protocol'] = $this->data['UsersOccurrences']['protocol'];
            $this->History->save($log);
            $this->Session->setFlash('<div class="alert alert-success">Enviado com sucesso!</div>');
        }
        else
        {
            $this->data = $this->UsersOccurrences->find('first', array('recursive'=>2, 'fields' => '','conditions' => array('Occurrence.id' => $id)));
        }
    }
    
    function resolve($id)
    {
        $this->request->data['Occurrence']['id']=$id;
        $this->request->data['Occurrence']['status']='Solucionada';
        if($this->request->data)
        {
//            if(!isset($this->request->data['Provider']['type'])){$this->request->data['Page']['type'] = 0;}
            
            if ($this->Occurrence->save($this->request->data))
            {
                // Set a session flash message and redirect.
                $this->Session->setFlash('<div class="alert alert-success">Solucionado com Sucesso!</div>');
                
            }
         }
         
         $this->redirect(array('action' => 'view','new'));
    }
    
    function history($id)
    {
        $this->loadModel('History');
        $Histories = $this->History->find('all', array('conditions'=>array('occurrence_id'=>$id)));
        $this->set('Histories', $Histories);
        
        $this->loadModel('User');
        $users = $this->User->find('list');
        $this->set('users', $users);
       
        $this->loadModel('Institution');
        $institutions = $this->Institution->find('list');
        $this->set('institutions', $institutions);
    }
    
    function delete($id)
    {
        $id_usersoccurrences = $this->UsersOccurrences->find('first', array('conditions'=>array('occurrence_id'=>$id)));
        $this->Occurrence->delete($id);
        $this->UsersOccurrences->delete($id_usersoccurrences['UsersOccurrences']['id']);
        
        $this->Session->setFlash('<div class="alert alert-success"><div class="alert alert-success">Removido com sucesso!</div>');
        $this->redirect(array('action' => 'index'));
    }
}
